<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    
 *
 * 预存款  2017-03-11 
 * 
 */
namespace osc\mobile\controller;

use osc\common\controller\Base;
use \think\Db;
use think\Request;

class Predeposit extends Base
{
	
	function check_login(){
		
		$uid=is_login();
		
		if(!$uid){			
			$this->redirect('login/login');					
		}

		$username = session('username');
		
		if(!$username)
		{
			$this->redirect('login/login');					
		}
		return $uid;
	}

	function getUserinfo()
	{
		if(request()->isPost()){
			
			$data=input('post.');
			//var_dump($data);
			
			if($data['mobile'])
			{
				$ret = Db::name('member')->where('username',$data['mobile'])->find();
				//return $ret;
				//var_dump($ret);
				$dt['nickname'] = $ret['nickname'];
				$dt['username'] = $ret['username'];
				$dt['idcardname'] = $ret['idcardname'];
				//$dt['idcard'] = $ret['username'];
				//$dt = $ret['username'];
				//echo json_encode($dt['nickname'],JSON_UNESCAPED_UNICODE);
				return array($dt['idcardname']);
				
			}


		}
		//return $this->fetch();
	}
	
	function index(){
		
		$uid=$this->check_login();
		$username = session('username');
		if(!$username)
		{
			$this->redirect('login/login');					
		}

		$start = input('param.start');
		$end = input('param.end');

		if($start && $end){
			$map = [
					'username' => $username,
					'dt' => array(['>',strtotime($start)],['<',strtotime($end)])
			];
		}
		$map['username'] = $username;

		$list = Db::name('contract_increase')
				->where($map)
				->order('dt desc')
				->paginate(5,false, [
						'query' => Request::instance()->param(),//不丢失已存在的url参数
				]);

		$page=$list->render(); //获取分页
		$user_info=Db::name('member')->where(array('uid'=>$uid))->find();
		$user_info['predeposit'] = (int)$user_info['predeposit'];
		$this->assign('user_info',$user_info);
		$this->assign('start',$start);
		$this->assign('end',$end);
		$this->assign('list',$list);
		$this->assign('page',$page);
		$this->assign('empty',"<span style='margin-left:20px;'>没有数据</span>");
				
		$this->assign('top_title','我的金豆');
		$this->assign('SEO',['title'=>'我的金豆-'.config('SITE_TITLE')]);
				
		return $this->fetch();
	}

	function recharge_rf()
	{

		$this->assign('list',Db::name('company_bank')->select());
		$this->assign('top_title','充值');
		$this->assign('SEO',['title'=>'充值-'.config('SITE_TITLE')]);
		return $this->fetch();
	}
	
	function recharge(){
		
		if(in_wechat()){
			$wechat=wechat();
			//调用微信收货地址接口，需要开通微信处理
			$this->assign('signPackage',$wechat->getJsSign(request()->url(true)));	
		}
		
		$uid=$this->check_login();
		
		if(request()->isPost()){
			
			$api=osc_service('common','Predeposit');
			
			if(in_wechat()){
				$pay_code='weixin';
			}else{
				$pay_code='alipay';
			}


			
			$order=$api->recharge($uid,$pay_code,input('param.money'));
			
			if(isset($order['error'])){
				return array('error'=>$order['error']);
			}
			
			if(in_wechat()){
				
				$pay=new \osc\mobile\controller\Payment();
				
				$order['notify_url']=request()->domain().url('Predeposit/jsskd_notify');
				
				return $pay->getBizPackage($order);
				
			}else{
				
				$config=payment_config('alipay');
			
				$alipay_config = array(
						"service"       => 'alipay.wap.create.direct.pay.by.user',
						"partner"       => $config['partner'],
						"seller_id"     => $config['partner'],
						"key"			=> $config['key'],
						"payment_type"	=> 1,
						"notify_url"	=> request()->domain().url('Predeposit/alipay_notify'),
						"return_url"	=> request()->domain().url('Predeposit/alipay_return'),
						"_input_charset"=> trim(strtolower(strtolower('utf-8'))),
						"out_trade_no"	=> $order['pay_order_no'],
						"subject"		=> $order['subject'],
						"total_fee"		=> $order['pay_total'],
						"show_url"		=> '',
						'transport'		=>'http',
						'sign_type'		=>strtoupper('MD5'),
						//"app_pay"	=> "Y",//启用此参数能唤起钱包APP处理宝
						"body"			=> '',								
				);
	
			
				$alipay = new \payment\alipay\Alipay($alipay_config,'mobile');
				
				$url = $alipay->get_payurl();
				
				return array('success'=>1,'type'=>'alipay','url'=>$url);
					
				}
			
		}
		
		$this->assign('top_title','充值');
		$this->assign('SEO',array('title'=>'充值-'.config('SITE_TITLE')));
		return $this->fetch();
	}

    //用户转让接口
	function usertf()
	{
		$user = session('username');

		if(request()->isPost()){

			$data=input('post.');
			$data['token']  = input('post.__token__/s', null);

			return $r=osc_service('common','Member')->usertf($data);
		}

		$into = Db::name('usertf')->where(array('username'=>$user))->order('dt desc')->limit(50)->select();
		$out = Db::name('usertf')->where(array('mobile'=>$user))->order('dt desc')->limit(50)->select();

		$list = array_merge($into,$out);

		array_multisort(array_column($list,'dt'),SORT_DESC,$list);

		$this->assign('list',$list);
		$this->assign('user',$user);
		$this->assign('top_title','金豆转让');
		$this->assign('SEO',array('title'=>'金豆转让-'.config('SITE_TITLE')));
		return $this->fetch();

	}

	//用户转让接口
	function pointstf()
	{
		$user = session('username');

		if(request()->isPost()){

			$data=input('post.');
			$data['token']  = input('post.__token__/s', null);

//			print_r($data);exit;

			return $r=osc_service('common','Member')->pointstf($data);

		}
		
		$list = Db::name('pointstf')->where(array('username'=>$user))->order('dt desc')->limit(50)->select();

		$this->assign('list',$list);
		$this->assign('top_title','金豆A转B');
		$this->assign('SEO',array('title'=>'金豆A转B-'.config('SITE_TITLE')));
		return $this->fetch();

	}

	/**
	 * 购买
	 * @return array
	 */
	function pay(){

		$api=osc_service('common','Predeposit');
		
		$data=input('param.');

		$post['uid']=member('uid');
		$post['type']=$data['type'];
		$post['shipping_method']=config('default_transport_id');
		$post['city_id']=$data['city_id'];
		$post['address_id']=$data['address_id'];
		$post['comment']=$data['comment'];	
		$post['goods_id']=$data['goods_id'];
		$post['apply']=$data['apply'];
		$post['username']=member('username');
		$post['m_total_buy']=member('m_total_buy');

		$r=$api->pay($post);

		if(isset($r['error'])){
			return array('error'=>$r['error']);
		}else{
			return array('success'=>'购买成功!');
		}

	}

	//处理宝异步通知
	function alipay_notify(){
		
		$alipay= new \payment\alipay\Alipay(payment_config('alipay'));	
		
		$verify_result = $alipay->verifyNotify();
		
		if($verify_result) {		
			
			$post=input('post.');
			
			$order=Db::name('predeposit')->where('order_num_alias',$post['out_trade_no'])->find();
			
			if($post['trade_status'] == 'TRADE_FINISHED') {				
				
		    }elseif($post['trade_status'] == 'TRADE_SUCCESS') {		
				
				if($order&&($order['pay_status']!=1)){
					
					$api=osc_service('common','Predeposit');
										
					$api->update_recharge_order($order['p_id'],$order['uid'],$order['money']);
					
					echo "success";		
									
				}else{
					echo "fail";
				}		        
				
		    }			
			
		}else{
			
			echo "fail";
		}
	}
	//处理宝同步通知
	function alipay_return(){
		
		$alipay= new \payment\alipay\Alipay(payment_config('alipay'));		
		//对进入的参数进行远程数据判断
		$verify = $alipay->return_verify();
	
		if($verify){
		
			$get=input('param.');
			
			$order=Db::name('predeposit')->where('order_num_alias',$get['out_trade_no'])->find();
			
			if($order['pay_status']==1){
				@header("Location: ".url('pay_success/recharge'));	
				die;
			}
			
			if($order&&($order['pay_status']!=1)){
				//处理完成
				if($get['trade_status']=='TRADE_SUCCESS'){
										
					$api=osc_service('common','Predeposit');
					
					$api->update_recharge_order($order['p_id'],$order['uid'],$order['money']);
					
					@header("Location: ".url('pay_success/recharge'));	
				}						
			}else{
				die('订单不存在');
			}
			
		}else{
			die('处理失败');
		}
	}
	
	public function jsskd_notify(){
		
		if(wechat()->checkPaySign()){
			
			$sourceStr = file_get_contents('php://input');		
		 
	        // 读取数据
	        $postObj = simplexml_load_string($sourceStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		 
			if (!$postObj) {
	       		 echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
	        } else {
			
				$order=Db::name('predeposit')->where('order_num_alias',$postObj->out_trade_no)->find();		
					
				if($order&&($order['pay_status']!=1)){
										
					$api=osc_service('common','Predeposit');
					
					$api->update_recharge_order($order['p_id'],$order['uid'],$order['money']);
					
					echo "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";	
									
				}else{
					echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
				}	
				
	        }			
			
		}else{  
			
			echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
			
		}
		die;
	}
	
}